package com.jielihaofeng.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Johnnie Wind
 * @description Routing 消费者
 * @date 2021/11/29 17:48
 */
public class Consumer_Routing2 {
    public static void main(String[] args) throws IOException, TimeoutException {

        // 1. 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();

        // 2. 设置连接参数
        connectionFactory.setHost("47.113.86.188");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/wzy");
        connectionFactory.setUsername("wuzhengyu");
        connectionFactory.setPassword("123456");

        // 3. 获取连接
        Connection connection = connectionFactory.newConnection();

        // 4. 创建 Channel
        Channel channel = connection.createChannel();

        String queue1Name = "test_direct_queue1";
        String queue2Name = "test_direct_queue2";


        /*
         * queue：队列名称
         * autoAck：是否自动确认
         * callback：回调对象
         */
        // 6. 接收消息
        Consumer consumer = new DefaultConsumer(channel) {

            /*
             * 回调方法，收到信息后执行该方法
             * consumerTag：标识
             * envelope：获取一些信息，交换机，路由key
             * properties：配置信息
             * body：数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                System.out.println("consumerTag：" + consumerTag);
//                System.out.println("Exchange：" + envelope.getExchange());
//                System.out.println("RoutingKey()：" + envelope.getRoutingKey());
//                System.out.println("properties：" + properties);
                System.out.println("body：" + new String(body));
                System.out.println("将日志信息打印到控制台......");
            }
        };
        channel.basicConsume(queue2Name, true, consumer);

        // 不要释放资源
    }
}
